/**
 * 用户管理
 */

//导入相应的库
import express from 'express';

//导入数据库连接
import conn from './../db/db'

import config from '../src/config';
import {basename} from 'path'

import formidable from 'formidable'

import md5 from 'blueimp-md5'
const S_KEY = '@WaLQ1314?.LqFtK.Com.#'; // 云

/**
 * 用户名和密码登录
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function loginPwd(req,res){
    // 获取数据
    const user_name = req.body.name;
    const user_pwd = md5(md5(req.body.pwd) + S_KEY);
    const captcha = req.body.captcha.toLowerCase();

    console.log(user_name+user_pwd+captcha);

    // 验证图形验证码是否正确
    if (captcha !== config.tmp_captcha) {
        res.json({err_code: 0, message: '图形验证码不正确!'});
        return;
    }

    config.tmp_captcha = '';
     查询数据
    let sqlStr = "SELECT * FROM user_info WHERE user_name = '" + user_name + "' LIMIT 1";
    nn.query(sqlStr, (error, results, fields) => {
      if (error) {
          res.json({err_code: 0, message: '用户名不正确!'});
      } else {
          results = JSON.parse(JSON.stringify(results));
          if (results[0]) {  // 用户已经存在
              // 验证密码是否正确
              if (results[0].user_pwd !== user_pwd) {
                  res.json({err_code: 0, message: '密码不正确!'});
              } else {
                  req.session.userId = results[0].id;
                  res.json({
                      success_code: 200,
                      message: {
                          id: results[0].id,
                          user_name: results[0].user_name || '',
                          user_nickname: results[0].user_nickname || '',
                          user_phone: results[0].user_phone || '',
                          user_sex: results[0].user_sex || '',
                          user_address: results[0].user_address || '',
                          user_sign: results[0].user_sign || '',
                          user_birthday: results[0].user_birthday || '',
                          user_avatar: results[0].user_avatar || ''
                      },
                      info: '登录成功!'
                  });
              }
          } else { // 新用户
              const addSql = "INSERT INTO user_info(user_name, user_pwd, user_avatar) VALUES (?, ?, ?)";
              const addSqlParams = [user_name, user_pwd, 'http://localhost:' + config.port + '/avatar_uploads/avatar_default.jpg'];
              conn.query(addSql, addSqlParams, (error, results, fields) => {
                  results = JSON.parse(JSON.stringify(results));
                  if (!error) {
                      req.session.userId = results.insertId;
                      let sqlStr = "SELECT * FROM user_info WHERE id = '" + results.insertId + "' LIMIT 1";
                      conn.query(sqlStr, (error, results, fields) => {
                          if (error) {
                              res.json({err_code: 0, message: '注册失败'});
                          } else {
                              results = JSON.parse(JSON.stringify(results));
                              res.json({
                                  success_code: 200,
                                  message: {
                                      id: results[0].id,
                                      user_name: results[0].user_name || '',
                                      user_nickname: results[0].user_nickname || '',
                                      user_avatar: results[0].user_avatar || ''
                                  }
                              });
                          }
                      });
                  }
              });
          }
      }
    });
}

/**
 * 根据session中的用户id获取用户信息
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function getUserInfo(req,res){
     // 获取参数
   let userId = req.query.user_id || req.session.userId;
   
   let sqlStr = "SELECT * FROM user_info WHERE id = " + userId + " LIMIT 1";
   conn.query(sqlStr, (error, results, fields) => {
       if (error) {
           res.json({err_code: 0, message: '请求用户数据失败'});
       } else {
           results = JSON.parse(JSON.stringify(results));
           if (!results[0]) {
               delete req.session.userId;
               res.json({error_code: 1, message: '请先登录'});
           } else {
               res.json({
                   success_code: 200,
                   message: {
                       id: results[0].id,
                       user_name: results[0].user_name || '',
                       user_nickname: results[0].user_nickname || '',
                       user_phone: results[0].user_phone || '',
                       user_sex: results[0].user_sex || '',
                       user_address: results[0].user_address || '',
                       user_sign: results[0].user_sign || '',
                       user_birthday: results[0].user_birthday || '',
                       user_avatar: results[0].user_avatar || ''
                   },
               });
           }
       }
   });
}


/**
 * 退出登录
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function loginout(req,res){

    // 清除session中userId
    delete  req.session.userId;
	
    res.json({
        success_code: 200,
        message: "退出登录成功"
    });
}

/**
 * 修改用户信息 
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function changeUserMsg(req,res){
    // 获取客户端传过来的用户信息
	const form = new formidable.IncomingForm();
    form.uploadDir = config.uploadsAvatarPath;  // 上传图片放置的文件夹
    form.keepExtensions = true; // 保持文件的原始扩展名
    form.parse(req, (err, fields, files)=>{
    if(err){
        return next(err);
    }
    let id = fields.id;
    let user_nickname = fields.user_nickname || '';
    let user_sex = fields.user_sex || '';
    let user_address = fields.user_address || '';
    let user_birthday = fields.user_birthday || '';
    let user_sign = fields.user_sign || '';
    let user_avatar = 'http://localhost:' + config.port + '/avatar_uploads/avatar_default.jpg';
    if(files.user_avatar){
        user_avatar = 'http://localhost:' + config.port + '/avatar_uploads/' + basename(files.user_avatar.path); 
    }
    // 验证
    if (!id) {
        res.json({err_code: 0, message: '修改用户信息失败!'});
    }
    // 更新数据
    let sqlStr = "UPDATE user_info SET user_nickname = ? , user_sex = ?, user_address = ?, user_birthday = ?, user_sign = ?, user_avatar = ? WHERE id = " + id;
    let strParams = [user_nickname, user_sex, user_address, user_birthday, user_sign, user_avatar];
    conn.query(sqlStr, strParams, (error, results, fields) => {
        if (error) {
            console.log(error);
            res.json({err_code: 0, message: '修改用户信息失败!'});
        } else {
            res.json({success_code: 200, message: '修改用户信息成功!'});
        }
    });
  });
}

/**
 * 修改用户密码
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function changeUserPwd(req,res){
    // 获取数据
    let id = req.body.id;
    let oriPwd = '';
    let newPwd = md5(md5(req.body.newPwd) + S_KEY);
    if(req.body.oriPwd){
        oriPwd = md5(md5(req.body.oriPwd) + S_KEY);
    }

    let sqlStr = "SELECT * FROM user_info WHERE id = " + id;
    conn.query(sqlStr, (error, results, fields) => {
        if (error) {
			console.log(error);
            res.json({err_code: 0, message: '查询失败!'});
        } else {
            results = JSON.parse(JSON.stringify(results));
            if (results[0]) { // 用户存在
                if(!results[0].user_pwd || (results[0].user_pwd && oriPwd === results[0].user_pwd)){
                    let sqlStr = "UPDATE user_info SET user_pwd = ? WHERE id = " + id;
                    conn.query(sqlStr, [newPwd], (error, results, fields) => {
                        if(!error){
                            res.json({success_code: 200, message: '密码修改成功!'});
                        }
                    });
                }else if(oriPwd != results[0].user_pwd){
                    res.json({err_code: 0, message: '输入的原始密码错误!'});
                }
            } else { 
                res.json({err_code: 0, message: '非法用户!'});
            }
        }
    });
}

/**
 * 修改手机
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function changeUserPhone(req,res){
     // 获取数据
     const id = req.body.id;
     const phone = req.body.phone;
     const code = req.body.code;
     // 验证验证码是否正确
     if (config.users[phone] !== code) {
         res.json({err_code: 0, message: '验证码不正确!'});
     }
     // 查询数据
     delete  config.users[phone];
 
     let sqlStr = "UPDATE user_info SET user_phone = " + phone + " WHERE id = " + id;
 
     conn.query(sqlStr, (error, results, fields) => {
         if (error) {
             res.json({err_code: 0, message: '修改失败'});
       console.log(error);
         } else {
             res.json({success_code: 200, message: '修改成功'});
         }
     });
}
/**
 * 获取所有用户信息
 * @param {express.Request} req 
 * @param {express.Response} res 
 */
function adminAllusers(req,res){

    let sqlStr = 'SELECT id, user_name, user_phone, user_nickname, user_address FROM user_info';
    conn.query(sqlStr, (error, results, fields) => {
        if (error) {
			console.log(error);
            res.json({err_code: 0, message: '请求用户数据失败'});
        } else {
            results = JSON.parse(JSON.stringify(results));
            res.json({success_code: 200, message: results});
        }
    });
}

export default {
  loginPwd,
  getUserInfo,
  loginout,
  changeUserMsg,
  changeUserPwd,
  changeUserPhone,
  adminAllusers
}
